package com.example.shipback.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * Converts a Java object to a JSON string.
     *
     * @param object the Java object to convert
     * @return JSON string representation of the object
     * @throws JsonProcessingException if the object cannot be converted to JSON
     */
    public static String toJson(Object object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * Converts a JSON string to a Java object of the specified class.
     *
     * @param json the JSON string
     * @param clazz the target class to convert to
     * @param <T> the type of the desired object
     * @return the Java object
     * @throws JsonProcessingException if the JSON string cannot be converted to the object
     */
    public static <T> T fromJson(String json, Class<T> clazz) throws JsonProcessingException {
        return objectMapper.readValue(json, clazz);
    }

    /**
     * Converts a JSON string to a JsonNode object for tree traversal or manipulation.
     *
     * @param json the JSON string
     * @return JsonNode object
     * @throws JsonProcessingException if the JSON string cannot be converted to JsonNode
     */
    public static JsonNode parse(String json) throws JsonProcessingException {
        return objectMapper.readTree(json);
    }

    /**
     * Pretty prints a JSON string.
     *
     * @param json the JSON string
     * @return pretty printed JSON string
     * @throws JsonProcessingException if the JSON string cannot be pretty printed
     */
    public static String prettyPrint(String json) throws JsonProcessingException {
        JsonNode jsonNode = objectMapper.readTree(json);
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    }

    /**
     * Converts a Java object to a pretty-printed JSON string.
     *
     * @param object the Java object to convert
     * @return pretty printed JSON string representation of the object
     * @throws JsonProcessingException if the object cannot be converted to JSON
     */
    public static String toPrettyJson(Object object) throws JsonProcessingException {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }
}
